package com.ecwid.consul.json;

import com.google.gson.*;
import com.google.gson.annotations.SerializedName;
import com.vlefen.springcloud.grpc.consul.ConsulService;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

public class GsonFactory {
    private static final Gson GSON = new GsonBuilder()
            .registerTypeAdapter(ConsulService.class, new ConsulServiceSerializer())
            .create();

    public GsonFactory() {
    }

    public static Gson getGson() {
        return GSON;
    }


    static class ConsulServiceSerializer implements JsonSerializer<ConsulService> {

        @Override
        public JsonElement serialize(ConsulService src, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject jsonObject = new JsonObject();

            if (src.check != null) {
                jsonObject.add("Check", GSON.toJsonTree(src.check));
            }

            if (src.checks != null) {
                jsonObject.add("Checks", GSON.toJsonTree(src.checks));
            }

            Field[] fields = ConsulService.class.getSuperclass().getDeclaredFields();
            for (Field field : fields) {
                SerializedName sn = field.getAnnotation(SerializedName.class);
                if (jsonObject.has(sn.value())) {
                    continue;
                }

                try {
                    field.setAccessible(true);
                    Object fieldValue = field.get(src);
                    if (null != fieldValue) {
                        jsonObject.add(sn.value(), GSON.toJsonTree(fieldValue));
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }

            return jsonObject;

        }
    }
}
